"""
【更新通知 观察者】
观察者模式(Observer Pattern)
定义一对多的依赖关系，让多个观察者对象同时监听某一个主题对象，并在主题对象变化时得到通知。这个模式使主题对象和观察者对象可以相互独立变化。

"""


class Subject:
    def __init__(self):
        self.observers = []

    def add_observer(self, observer):
        self.observers.append(observer)

    def remove_observer(self, observer):
        self.observers.remove(observer)

    def notify_observers(self, data):
        for observer in self.observers:
            observer.update(data)


class Observer:
    def update(self, data):
        pass


class Sensor(Subject):
    def read_sensor_data(self):
        data = 42  # read sensor data here
        self.notify_observers(data)


class Display(Observer):
    def update(self, data):
        print(f"Displaying sensor data: {data}")


class Logging(Observer):
    def update(self, data):
        print(f"Logging sensor data: {data}")


sensor = Sensor()
display = Display()
logging = Logging()

sensor.add_observer(display)
sensor.add_observer(logging)

sensor.read_sensor_data()
"""
Displaying sensor data: 42
Logging sensor data: 42
"""
